package com.myalibaba.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Redis 分布式锁类
 * 在 lock 方法中，通过 setIfAbsent 方法尝试获取锁，如果成功返回 true，否则返回 false。
 * 在 unlock 方法中，直接使用 delete 方法删除锁。
 */
@Configuration
public class RedisDistributedLock {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String LOCK_PREFIX = "lock:";
    private static final long DEFAULT_EXPIRE_TIME = 30; // 默认过期时间，单位：秒

    public boolean lock(String lockKey) {
        String key = LOCK_PREFIX + lockKey;
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, "locked", DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);
        return success != null && success;
    }

    public void unlock(String lockKey) {
        String key = LOCK_PREFIX + lockKey;
        redisTemplate.delete(key);
    }


    public void setValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }
    public void setHashValue(String hashKey, String field, String value) {
        redisTemplate.opsForHash().put(hashKey, field, value);
    }

    public String getHashValue(String hashKey, String field) {
        return (String) redisTemplate.opsForHash().get(hashKey, field);
    }
}
